package com.xyhs.b2c.oauth.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ljp
 * @apiNote
 * @date 9:34 2020/3/10
 **/
@Service("myUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {


    private Map<String,JSONObject> userMap = new HashMap<>();

    public MyUserDetailsService(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userName","ljp");
        jsonObject.put("password","123456");
        jsonObject.put("role","admin");
        userMap.put("ljp",jsonObject);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("userName","xyhs");
        jsonObject1.put("password","123456");
        jsonObject1.put("role","user");
        userMap.put("xyhs",jsonObject1);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(userMap.get(username) == null){
            throw new UsernameNotFoundException("系统用户 " + username + " 不存在!");
        }
        JSONObject jsonObject = userMap.get(username);
        UserDetails user = User.withUsername(jsonObject.getString("userName"))
                .password(new BCryptPasswordEncoder().encode(jsonObject.getString("password")) )
                .roles(jsonObject.getString("role")).authorities(AuthorityUtils.commaSeparatedStringToAuthorityList(jsonObject.getString("role"))).build();

        return user;
    }
}
